package com.fire.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fire.util.ConstantKeys;
import com.fire.util.base.TokenUtil;

@Component
public class BaseController {

	@Autowired
	private TokenUtil tokenUtil;

	/**
	 * JSON数据初始化
	 * 
	 * @param request
	 * @return
	 */
	public JSONObject initJsonParam(HttpServletRequest request) {

		JSONObject jsonObject = new JSONObject();
		byte buffer[];
		try {
			buffer = getRequestPostBytes(request);
			String charEncoding = request.getCharacterEncoding();
			if (charEncoding == null) {
				charEncoding = "UTF-8";
			}
			String param = new String(buffer, charEncoding);
			if (null == param || "".equals(param)) {
				param = "{}";
			}
			param = param.replaceAll("\\\\t", " ");
			jsonObject = JSONObject.parseObject(param);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return jsonObject;
	}

	/**
	 * 解析Token,获取当前userId
	 * 
	 * @param request
	 * @return
	 */
	public Integer currentUserId(HttpServletRequest request) {
		String token = request.getHeader(ConstantKeys.REQUEST_HEADER);
		DecodedJWT jwt = tokenUtil.verifyJwt(token);
		return jwt.getClaim("userId").asInt();
	}

	public static byte[] getRequestPostBytes(HttpServletRequest request) throws IOException {
		int contentLength = request.getContentLength();
		if (contentLength < 0) {
			return null;
		}
		byte buffer[] = new byte[contentLength];
		for (int i = 0; i < contentLength;) {

			int readlen = request.getInputStream().read(buffer, i, contentLength - i);
			if (readlen == -1) {
				break;
			}
			i += readlen;
		}
		return buffer;
	}

}
